<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拖陪玩结算器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
            padding: 15px;
            color: #333;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .app-container {
            max-width: 450px;
            width: 100%;
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.25);
        }
        
        .header {
            text-align: center;
            padding: 20px 0;
            background: linear-gradient(to right, #3a7bd5, #00d2ff);
            color: white;
            position: relative;
        }
        
        .header h1 {
            font-size: 24px;
            margin-bottom: 8px;
            font-weight: 700;
        }
        
        .contact-info {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .expiry-info {
            background: rgba(231, 76, 60, 0.1);
            padding: 12px;
            text-align: center;
            font-size: 16px;
            color: #e74c3c;
            font-weight: bold;
            border-bottom: 1px solid #f5f5f5;
            display: none;
        }
        
        .input-section {
            padding: 20px;
            background-color: #f8f9fa;
        }
        
        .input-row {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .input-group {
            flex: 1;
        }
        
        .input-group label {
            display: block;
            font-weight: bold;
            margin-bottom: 8px;
            font-size: 15px;
            color: #2c3e50;
        }
        
        .input-group input, .input-group select {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 16px;
            background: white;
        }
        
        .fee-toggle {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .fee-toggle label {
            flex: 1;
            font-weight: bold;
            font-size: 15px;
        }
        
        .switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 24px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .slider {
            background-color: #2ecc71;
        }
        
        input:checked + .slider:before {
            transform: translateX(26px);
        }
        
        .result-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin: 15px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            border: 1px solid #eee;
        }
        
        .result-item {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            border-bottom: 1px solid #f5f5f5;
            font-size: 16px;
        }
        
        .result-item:last-child {
            border-bottom: none;
        }
        
        .highlight {
            color: #e74c3c;
            font-weight: bold;
            font-size: 17px;
        }
        
        .price-section {
            display: flex;
            align-items: center;
            background: white;
            border-radius: 15px;
            padding: 15px;
            margin: 0 15px 15px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            gap: 15px;
        }
        
        .price-input {
            flex: 1;
        }
        
        .price-input label {
            display: block;
            font-weight: bold;
            margin-bottom: 8px;
            font-size: 15px;
        }
        
        .price-input input {
            width: 100%;
            padding: 14px 15px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 18px;
            background: #f8f9fa;
        }
        
        .final-amount {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-width: 90px;
        }
        
        .final-amount label {
            font-weight: bold;
            font-size: 15px;
        }
        
        .final-amount-value {
            font-size: 24px;
            color: #e74c3c;
            font-weight: bold;
            margin-top: 5px;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
            padding: 0 15px;
            margin-bottom: 15px;
        }
        
        .action-btn {
            color: white;
            border: none;
            border-radius: 12px;
            padding: 15px 0;
            font-size: 16px;
            cursor: pointer;
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .action-btn:active {
            transform: translateY(2px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .copy-btn {
            background: linear-gradient(to right, #3498db, #2980b9);
        }
        
        .generate-btn {
            background: linear-gradient(to right, #2ecc71, #27ae60);
        }
        
        .history-btn {
            background: linear-gradient(to right, #9b59b6, #8e44ad);
            color: white;
            border: none;
            border-radius: 12px;
            padding: 15px 0;
            font-size: 16px;
            cursor: pointer;
            width: calc(100% - 30px);
            margin: 0 15px 15px;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .history-btn:active {
            transform: translateY(2px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .encrypt-btn {
            background: linear-gradient(to right, #e67e22, #d35400);
            color: white;
            border: none;
            border-radius: 12px;
            padding: 15px 0;
            font-size: 16px;
            cursor: pointer;
            width: calc(100% - 30px);
            margin: 0 15px 15px;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .encrypt-btn:active {
            transform: translateY(2px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .footer {
            display: flex;
            justify-content: space-around;
            padding: 15px 0;
            background: white;
            border-top: 1px solid #eee;
        }
        
        .social-btn {
            background: none;
            border: none;
            font-size: 18px;
            color: #3498db;
            cursor: pointer;
            padding: 8px 20px;
            border-radius: 50px;
            transition: all 0.3s ease;
        }
        
        .social-btn:active {
            background: rgba(52, 152, 219, 0.1);
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 100;
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background: white;
            border-radius: 20px;
            width: 90%;
            max-width: 400px;
            max-height: 80vh;
            overflow-y: auto;
            padding: 20px;
            position: relative;
            box-shadow: 0 15px 30px rgba(0,0,0,0.3);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #7f8c8d;
            width: 40px;
            height: 40px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 50%;
            transition: background 0.3s;
        }
        
        .modal-close:active {
            background: rgba(127, 140, 141, 0.2);
        }
        
        .expiry-options {
            margin: 20px 0;
        }
        
        .expiry-options label {
            display: block;
            font-weight: bold;
            margin-bottom: 15px;
            font-size: 18px;
        }
        
        .expiry-select {
            width: 100%;
            padding: 14px 15px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 16px;
            background: white;
        }
        
        .share-link {
            margin-top: 20px;
        }
        
        .share-link input {
            width: 100%;
            padding: 14px 15px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 16px;
            margin-bottom: 10px;
        }
        
        .copy-link-btn {
            width: 100%;
            padding: 14px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            cursor: pointer;
        }
        
        .history-item {
            padding: 15px;
            border-bottom: 1px solid #f5f5f5;
        }
        
        .history-item:last-child {
            border-bottom: none;
        }
        
        .history-header {
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            font-size: 15px;
            margin-bottom: 8px;
        }
        
        .history-details {
            font-size: 14px;
            color: #7f8c8d;
            line-height: 1.5;
        }
        
        .history-details div {
            margin-bottom: 5px;
        }
        
        .empty-history {
            text-align: center;
            padding: 20px;
            color: #7f8c8d;
            font-size: 16px;
        }
        
        .expiry-label {
            display: block;
            margin-top: 15px;
            font-size: 16px;
            color: #7f8c8d;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- 应用头部 -->
        <div class="header">
            <h1>拖拖陪玩结算器</h1>
        </div>
        
        <!-- 有效期信息 -->
        <div class="expiry-info" id="expiryInfo">
            链接有效期至: <span id="expiryDate"></span>
        </div>
        
        <!-- 输入区域 -->
        <div class="input-section">
            <div class="input-row">
                <div class="input-group">
                    <label>派单：</label>
                    <input type="text" id="agent" placeholder="输入派单名">
                </div>
                <div class="input-group">
                    <label>陪陪：</label>
                    <input type="text" id="player" placeholder="输入陪陪名">
                </div>
            </div>
            
            <div class="input-row">
                <div class="input-group">
                    <label>老板：</label>
                    <input type="text" id="customer" placeholder="输入老板名">
                </div>
                <div class="input-group">
                    <label>类型：</label>
                    <input type="text" id="type" placeholder="输入类型">
                </div>
            </div>
            
            <div class="input-row">
                <div class="input-group">
                    <label>时长：</label>
                    <input type="number" id="duration" value="1" min="1">
                </div>
                <div class="input-group">
                    <label>折扣：</label>
                    <select id="discount">
                        <option value="1.00">无折扣</option>
                        <option value="0.99">99折</option>
                        <option value="0.98">98折</option>
                        <option value="0.97">97折</option>
                        <option value="0.96">96折</option>
                        <option value="0.95">95折</option>
                        <option value="0.94">94折</option>
                        <option value="0.93">93折</option>
                        <option value="0.92">92折</option>
                        <option value="0.91">91折</option>
                        <option value="0.90">9折</option>
                        <option value="0.89">89折</option>
                        <option value="0.88">88折</option>
                        <option value="0.87">87折</option>
                        <option value="0.86">86折</option>
                        <option value="0.85">85折</option>
                        <option value="0.84">84折</option>
                        <option value="0.83">83折</option>
                        <option value="0.82">82折</option>
                        <option value="0.81">81折</option>
                        <option value="0.80">8折</option>
                    </select>
                </div>
            </div>
            
            <!-- 团抽比例选择 -->
            <div class="input-row">
                <div class="input-group">
                    <label>团抽比例：</label>
                    <select id="groupCommissionRate">
                        <option value="0">无</option>
                        <option value="0.05" selected>5%</option>
                        <option value="0.10">10%</option>
                    </select>
                </div>
            </div>
            
            <!-- 费用开关 -->
            <div class="fee-toggle">
                <label>派抽 (15%)：</label>
                <label class="switch">
                    <input type="checkbox" id="platformToggle" checked>
                    <span class="slider"></span>
                </label>
            </div>
            
            <div class="fee-toggle">
                <label>接抽 (10%)：</label>
                <label class="switch">
                    <input type="checkbox" id="receiveToggle">
                    <span class="slider"></span>
                </label>
            </div>
            
            <div class="fee-toggle">
                <label>拉板 (5%)：</label>
                <label class="switch">
                    <input type="checkbox" id="boardToggle">
                    <span class="slider"></span>
                </label>
            </div>
        </div>
        
        <!-- 结果区域 -->
        <div class="result-container">
            <div class="result-item">
                <span>单号：</span>
                <span id="result-order">1</span>
            </div>
            <div class="result-item">
                <span>派单：</span>
                <span id="result-agent">小懒陪玩</span>
            </div>
            <div class="result-item">
                <span>陪陪：</span>
                <span id="result-player">-</span>
            </div>
            <div class="result-item">
                <span>老板：</span>
                <span id="result-customer">-</span>
            </div>
            <div class="result-item">
                <span>类型：</span>
                <span id="result-type">语音</span>
            </div>
            <div class="result-item">
                <span>时长：</span>
                <span id="result-duration">1小时</span>
            </div>
            <div class="result-item">
                <span>总价：</span>
                <span class="highlight" id="result-total">100</span>
            </div>
            <div class="result-item">
                <span>折扣后总价：</span>
                <span class="highlight" id="result-discounted-total">100</span>
            </div>
            <div class="result-item" id="group-result">
                <span>团抽：</span>
                <span id="result-group">0.00</span>
            </div>
            <div class="result-item" id="platform-result">
                <span>派抽：</span>
                <span id="result-platform">0.00</span>
            </div>
            <div class="result-item" id="receive-result">
                <span>接抽：</span>
                <span id="result-receive">0.00</span>
            </div>
            <div class="result-item" id="board-result">
                <span>拉板：</span>
                <span id="result-board">0.00</span>
            </div>
            <div class="result-item">
                <span>到手：</span>
                <span class="highlight" id="result-final">100.00</span>
            </div>
        </div>
        
        <!-- 金额区域 -->
        <div class="price-section">
            <div class="price-input">
                <label>金额：</label>
                <input type="number" id="price" value="100" min="0" step="5">
            </div>
            
            <div class="final-amount">
                <label>到手：</label>
                <div class="final-amount-value" id="final-amount">100.00</div>
            </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
            <button class="action-btn copy-btn" id="copyBtn">
                复制结单
            </button>
            <button class="action-btn generate-btn" id="generateBtn">
                生成结单
            </button>
        </div>
        
        <button class="history-btn" id="historyBtn">
            查看结算历史
        </button>
        
        <button class="encrypt-btn" id="encryptBtn">
            生成加密链接
        </button>
    </div>
    
    <!-- 加密链接模态框 -->
    <div class="modal" id="encryptModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>生成加密链接</h2>
                <button class="modal-close" id="closeModal">&times;</button>
            </div>
            
            <div class="expiry-options">
                <label>选择有效期：</label>
                <select class="expiry-select" id="expirySelect">
                    <option value="1">1个月</option>
                    <option value="2">2个月</option>
                    <option value="3">3个月</option>
                    <option value="6">6个月</option>
                    <option value="9">9个月</option>
                    <option value="12">12个月</option>
                </select>
                <span class="expiry-label">最长有效期为12个月</span>
            </div>
            
            <div class="share-link">
                <input type="text" id="shareLink" readonly>
                <button class="copy-link-btn" id="copyLinkBtn">复制链接</button>
            </div>
        </div>
    </div>
    
    <!-- 历史记录模态框 -->
    <div class="modal" id="historyModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>结算历史记录</h2>
                <button class="modal-close" id="closeHistoryModal">&times;</button>
            </div>
            
            <div id="historyList">
                <div class="empty-history">暂无历史记录</div>
            </div>
        </div>
    </div>
    
    <script>
        // DOM元素
        const agentInput = document.getElementById('agent');
        const playerInput = document.getElementById('player');
        const customerInput = document.getElementById('customer');
        const typeInput = document.getElementById('type');
        const durationInput = document.getElementById('duration');
        const priceInput = document.getElementById('price');
        const discountSelect = document.getElementById('discount');
        const groupCommissionRateSelect = document.getElementById('groupCommissionRate');
        
        const resultOrder = document.getElementById('result-order');
        const resultAgent = document.getElementById('result-agent');
        const resultPlayer = document.getElementById('result-player');
        const resultCustomer = document.getElementById('result-customer');
        const resultType = document.getElementById('result-type');
        const resultDuration = document.getElementById('result-duration');
        const resultTotal = document.getElementById('result-total');
        const resultDiscountedTotal = document.getElementById('result-discounted-total');
        const resultGroup = document.getElementById('result-group');
        const resultPlatform = document.getElementById('result-platform');
        const resultReceive = document.getElementById('result-receive');
        const resultBoard = document.getElementById('result-board');
        const resultFinal = document.getElementById('result-final');
        
        const finalAmount = document.getElementById('final-amount');
        const copyBtn = document.getElementById('copyBtn');
        const generateBtn = document.getElementById('generateBtn');
        const historyBtn = document.getElementById('historyBtn');
        const encryptBtn = document.getElementById('encryptBtn');
        const encryptModal = document.getElementById('encryptModal');
        const closeModal = document.getElementById('closeModal');
        const shareLinkInput = document.getElementById('shareLink');
        const copyLinkBtn = document.getElementById('copyLinkBtn');
        const expiryInfo = document.getElementById('expiryInfo');
        const expiryDate = document.getElementById('expiryDate');
        const expirySelect = document.getElementById('expirySelect');
        const historyModal = document.getElementById('historyModal');
        const closeHistoryModal = document.getElementById('closeHistoryModal');
        const historyList = document.getElementById('historyList');
        
        // 费用开关
        const platformToggle = document.getElementById('platformToggle');
        const receiveToggle = document.getElementById('receiveToggle');
        const boardToggle = document.getElementById('boardToggle');
        
        // 费用结果元素
        const platformResult = document.getElementById('platform-result');
        const receiveResult = document.getElementById('receive-result');
        const boardResult = document.getElementById('board-result');
        const groupResult = document.getElementById('group-result');
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', () => {
            // 首次加载时立即计算并初始化结果
            calculateSettlement();
            
            // 添加事件监听器
            generateBtn.addEventListener('click', saveAndCalculate);
            copyBtn.addEventListener('click', copyToClipboard);
            encryptBtn.addEventListener('click', showEncryptModal);
            closeModal.addEventListener('click', () => {
                encryptModal.style.display = 'none';
            });
            copyLinkBtn.addEventListener('click', copyShareLink);
            historyBtn.addEventListener('click', showHistory);
            closeHistoryModal.addEventListener('click', () => {
                historyModal.style.display = 'none';
            });
            
            // 当输入变化时重新计算
            const inputs = [agentInput, playerInput, customerInput, typeInput, 
                           durationInput, priceInput, discountSelect, groupCommissionRateSelect];
            inputs.forEach(input => {
                input.addEventListener('input', calculateSettlement);
                input.addEventListener('change', calculateSettlement);
            });
            
            // 费用开关变化时重新计算
            platformToggle.addEventListener('change', calculateSettlement);
            receiveToggle.addEventListener('change', calculateSettlement);
            boardToggle.addEventListener('change', calculateSettlement);
            
            // 检查URL参数
            checkUrlParams();
            
            // 初始化单号
            initOrderNumber();
        });
        
        // 初始化单号
        function initOrderNumber() {
            const now = new Date();
            const currentMonth = now.getMonth() + '-' + now.getFullYear();
            
            // 获取存储的月份和单号
            const storedMonth = localStorage.getItem('settlementMonth');
            const storedOrderNumber = localStorage.getItem('settlementOrderNumber');
            
            if (storedMonth === currentMonth && storedOrderNumber) {
                resultOrder.textContent = storedOrderNumber;
            } else {
                // 新月份，重置单号
                localStorage.setItem('settlementMonth', currentMonth);
                localStorage.setItem('settlementOrderNumber', '1');
                resultOrder.textContent = '1';
            }
        }
        
        // 获取下一个单号
        function getNextOrderNumber() {
            const now = new Date();
            const currentMonth = now.getMonth() + '-' + now.getFullYear();
            
            // 获取存储的月份和单号
            const storedMonth = localStorage.getItem('settlementMonth');
            const storedOrderNumber = parseInt(localStorage.getItem('settlementOrderNumber') || '1');
            
            if (storedMonth === currentMonth) {
                // 同一个月，递增单号
                const nextOrder = storedOrderNumber + 1;
                localStorage.setItem('settlementOrderNumber', nextOrder);
                return nextOrder;
            } else {
                // 新月份，重置单号
                localStorage.setItem('settlementMonth', currentMonth);
                localStorage.setItem('settlementOrderNumber', '1');
                return 1;
            }
        }
        
        // 检查URL参数
        function checkUrlParams() {
            const urlParams = new URLSearchParams(window.location.search);
            const token = urlParams.get('token');
            const expiry = urlParams.get('expiry');
            
            if (token && expiry) {
                const currentTime = new Date().getTime();
                const expiryTime = parseInt(expiry);
                
                if (currentTime > expiryTime) {
                    // 链接已过期
                    disableApp("链接已过期");
                    return;
                }
                
                // 隐藏加密按钮（只有主页面可以生成加密链接）
                encryptBtn.style.display = 'none';
                
                // 设置有效期
                setExpiryTime(expiryTime);
            } else {
                // 没有参数，可能是主页面
                // 显示加密按钮
                encryptBtn.style.display = 'block';
            }
        }
        
        // 设置有效期
        function setExpiryTime(endTime) {
            expiryInfo.style.display = 'block';
            
            // 格式化并显示到期日期
            const expiryDateObj = new Date(endTime);
            expiryDate.textContent = expiryDateObj.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
        
        // 禁用应用
        function disableApp(reason) {
            // 禁用所有输入和按钮
            const inputs = document.querySelectorAll('input');
            inputs.forEach(input => input.disabled = true);
            
            const buttons = document.querySelectorAll('button');
            buttons.forEach(button => button.disabled = true);
            
            // 显示过期信息
            expiryInfo.textContent = reason;
            expiryInfo.style.background = '#ffdddd';
            expiryInfo.style.color = '#e74c3c';
        }
        
        // 计算结算结果
        function calculateSettlement() {
            const price = parseFloat(priceInput.value) || 0;
            const duration = parseInt(durationInput.value) || 0;
            const discount = parseFloat(discountSelect.value) || 1;
            const groupRate = parseFloat(groupCommissionRateSelect.value) || 0;
            
            // 计算折扣后总价
            const discountedTotal = price * discount;
            
            // 根据开关状态计算各项费用
            let groupCommission = 0;
            let platformCommission = 0;
            let receiveCommission = 0;
            let boardCommission = 0;
            
            if (groupRate > 0) {
                groupCommission = discountedTotal * groupRate;
            }
            
            if (platformToggle.checked) {
                platformCommission = discountedTotal * 0.15;
            }
            
            if (receiveToggle.checked) {
                receiveCommission = discountedTotal * 0.10;
            }
            
            if (boardToggle.checked) {
                boardCommission = discountedTotal * 0.05;
            }
            
            // 计算到手金额
            const final = discountedTotal - groupCommission - platformCommission - receiveCommission - boardCommission;
            
            // 更新结果区域
            resultAgent.textContent = agentInput.value;
            resultPlayer.textContent = playerInput.value || '-';
            resultCustomer.textContent = customerInput.value || '-';
            resultType.textContent = typeInput.value;
            resultDuration.textContent = `${duration}小时`;
            resultTotal.textContent = price.toFixed(2);
            resultDiscountedTotal.textContent = discountedTotal.toFixed(2);
            resultGroup.textContent = groupCommission.toFixed(2);
            resultPlatform.textContent = platformCommission.toFixed(2);
            resultReceive.textContent = receiveCommission.toFixed(2);
            resultBoard.textContent = boardCommission.toFixed(2);
            resultFinal.textContent = final.toFixed(2);
            
            // 更新到手金额
            finalAmount.textContent = final.toFixed(2);
            
            // 根据状态显示/隐藏费用项
            groupResult.style.display = groupRate > 0 ? 'flex' : 'none';
            platformResult.style.display = platformToggle.checked ? 'flex' : 'none';
            receiveResult.style.display = receiveToggle.checked ? 'flex' : 'none';
            boardResult.style.display = boardToggle.checked ? 'flex' : 'none';
        }
        
        // 保存并计算
        function saveAndCalculate() {
            calculateSettlement();
            saveToHistory();
            
            // 添加视觉反馈
            generateBtn.innerHTML = '✓ 已生成';
            generateBtn.style.background = 'linear-gradient(to right, #27ae60, #2ecc71)';
            
            setTimeout(() => {
                generateBtn.innerHTML = '生成结单';
                generateBtn.style.background = 'linear-gradient(to right, #2ecc71, #27ae60)';
            }, 1500);
        }
        
        // 保存到历史记录
        function saveToHistory() {
            // 获取下一个单号
            const orderNumber = getNextOrderNumber();
            resultOrder.textContent = orderNumber;
            
            const settlement = {
                order: orderNumber,
                agent: agentInput.value,
                player: playerInput.value || '未填写',
                customer: customerInput.value || '未填写',
                type: typeInput.value,
                duration: durationInput.value + '小时',
                price: parseFloat(priceInput.value).toFixed(2),
                discount: parseFloat(discountSelect.value).toFixed(2),
                groupRate: parseFloat(groupCommissionRateSelect.value).toFixed(2),
                group: resultGroup.textContent,
                platform: platformToggle.checked ? resultPlatform.textContent : '0.00',
                receive: receiveToggle.checked ? resultReceive.textContent : '0.00',
                board: boardToggle.checked ? resultBoard.textContent : '0.00',
                final: resultFinal.textContent,
                timestamp: new Date().toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                })
            };
            
            // 获取现有历史记录
            let history = JSON.parse(localStorage.getItem('settlementHistory') || '[]');
            
            // 添加新记录到开头
            history.unshift(settlement);
            
            // 只保留最近10条记录
            if (history.length > 10) {
                history = history.slice(0, 10);
            }
            
            // 保存回localStorage
            localStorage.setItem('settlementHistory', JSON.stringify(history));
        }
        
        // 显示加密模态框
        function showEncryptModal() {
            // 显示模态框
            encryptModal.style.display = 'flex';
            
            // 生成分享链接
            generateShareLink();
        }
        
        // 生成分享链接
        function generateShareLink() {
            // 获取选择的月数
            const months = parseInt(expirySelect.value);
            
            // 计算过期时间（当前时间 + 月数）
            const expiryDate = new Date();
            expiryDate.setMonth(expiryDate.getMonth() + months);
            const expiryTime = expiryDate.getTime();
            
            // 生成随机令牌
            const token = generateToken();
            
            // 生成分享链接
            const shareLink = `${window.location.origin}${window.location.pathname}?token=${token}&expiry=${expiryTime}`;
            
            // 更新输入框
            shareLinkInput.value = shareLink;
            
            // 设置有效期
            setExpiryTime(expiryTime);
        }
        
        // 生成随机令牌
        function generateToken() {
            return 'token_' + Math.random().toString(36).substr(2, 12);
        }
        
        // 复制分享链接
        function copyShareLink() {
            shareLinkInput.select();
            document.execCommand('copy');
            
            // 添加视觉反馈
            copyLinkBtn.textContent = '✓ 已复制';
            copyLinkBtn.style.background = '#2980b9';
            
            setTimeout(() => {
                copyLinkBtn.textContent = '复制链接';
                copyLinkBtn.style.background = '#3498db';
            }, 1500);
        }
        
        // 显示历史记录
        function showHistory() {
            const history = JSON.parse(localStorage.getItem('settlementHistory') || '[]');
            
            if (history.length === 0) {
                historyList.innerHTML = '<div class="empty-history">暂无历史记录</div>';
            } else {
                let historyHTML = '';
                
                history.forEach((item, index) => {
                    historyHTML += `
                    <div class="history-item">
                        <div class="history-header">
                            <span>#${item.order} ${item.agent}的结单</span>
                            <span>${item.timestamp}</span>
                        </div>
                        <div class="history-details">
                            <div>陪陪: ${item.player} | 老板: ${item.customer}</div>
                            <div>类型: ${item.type} | 时长: ${item.duration}</div>
                            <div>总价: ${item.price} | 折扣: ${item.discount}</div>
                            <div>折扣后总价: ${(parseFloat(item.price) * parseFloat(item.discount)).toFixed(2)}</div>
                            <div>团抽(${item.groupRate*100}%): ${item.group}</div>
                            <div>派抽: ${item.platform} | 接抽: ${item.receive} | 拉板: ${item.board}</div>
                            <div>到手: <b>${item.final}</b></div>
                        </div>
                    </div>
                    `;
                });
                
                historyList.innerHTML = historyHTML;
            }
            
            historyModal.style.display = 'flex';
        }
        
        // 复制到剪贴板
        function copyToClipboard() {
            const text = `
单号：${resultOrder.textContent}
派单：${resultAgent.textContent}
陪陪：${resultPlayer.textContent}
老板：${resultCustomer.textContent}
类型：${resultType.textContent}
时长：${resultDuration.textContent}
总价：${resultTotal.textContent}
折扣后总价：${resultDiscountedTotal.textContent}
团抽：${resultGroup.textContent}
派抽：${resultPlatform.textContent}
接抽：${resultReceive.textContent}
拉板：${resultBoard.textContent}
到手：${resultFinal.textContent}
`;
            
            navigator.clipboard.writeText(text).then(() => {
                // 视觉反馈
                copyBtn.textContent = '✓ 已复制';
                copyBtn.style.background = 'linear-gradient(to right, #2980b9, #3498db)';
                
                setTimeout(() => {
                    copyBtn.textContent = '复制结单';
                    copyBtn.style.background = 'linear-gradient(to right, #3498db, #2980b9)';
                }, 1500);
            }).catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动选择并复制文本');
            });
        }
    </script>
</body>
</html>